package com.health.system.springSecurity;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

/**
 * 决策类（决定用户是否用权限访问所请求的资源）
 * 
 */
public class MyAccessDecisionManager implements AccessDecisionManager {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.security.access.AccessDecisionManager#decide(org.springframework.security.core.Authentication
	 *      用户所拥有的所有权限, java.lang.Object 请求的资源, java.util.Collection
	 *      访问所请求资源所需的权限信息)
	 */
	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		if (configAttributes == null) {
			return;
		}
		Iterator<ConfigAttribute> iterator = configAttributes.iterator();
		while (iterator.hasNext()) {
			ConfigAttribute configAttribute = iterator.next();
			String needPermission = ((SecurityConfig) configAttribute)
					.getAttribute();
			Collection<GrantedAuthority> gaCollection = authentication
					.getAuthorities();
			if (gaCollection != null) {
				for (GrantedAuthority ga : gaCollection) {
					if (needPermission.equals(ga.getAuthority())) {
						return;
					}
				}
			}
		}
		throw new AccessDeniedException("您无权访问该资源,请与管理员联系!");
	}

	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}

}